package com.ims.core.doc.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import com.ims.common.config.ImsConfig;
import com.ims.common.exception.ServiceException;
import com.ims.common.utils.DateUtils;
import com.ims.common.utils.StringUtils;
import com.ims.common.utils.file.FileUploadUtils;
import com.ims.common.utils.file.FileUtils;
import com.ims.common.utils.poi.NewExcelUtil;
import com.ims.core.doc.controller.vo.InvoiceCollectValidateVo;
import com.ims.core.doc.domain.TInInvoiceFolder;
import com.ims.core.doc.service.ITInInvoiceFolderService;
import com.ims.core.doc.vo.bwapi.InvoiceForRecogcollect;
import com.ims.core.enums.CollectType;
import com.ims.framework.config.ServerConfig;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.ims.common.annotation.Log;
import com.ims.common.core.controller.BaseController;
import com.ims.common.core.domain.AjaxResult;
import com.ims.common.enums.BusinessType;
import com.ims.core.doc.domain.TInCollect;
import com.ims.core.doc.service.ITInCollectService;
import com.ims.common.utils.poi.ExcelUtil;
import com.ims.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 发票采集Controller
 *
 * @author IMS
 * @date 2024-07-24
 */
@RestController
@RequestMapping("/doc/collect")
public class TInCollectController extends BaseController
{
    private final int MAX_FILE_QTY = 50;
    private final int MAX_EXCEL_LINE_QTY = 300;
    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private ITInCollectService tInCollectService;

    @Autowired
    private ITInInvoiceFolderService tInInvoiceFolderService;

    /**
     * 查询发票采集列表
     */
    @PreAuthorize("@ss.hasPermi('doc:collect:list')")
    @GetMapping("/list")
    public TableDataInfo list(TInCollect tInCollect)
    {
        startPage();
        List<TInCollect> list = tInCollectService.selectTInCollectList(tInCollect);
        return getDataTable(list);
    }

    /**
     * 导出发票采集列表
     */
    @PreAuthorize("@ss.hasPermi('doc:collect:export')")
    @Log(title = "发票采集", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TInCollect tInCollect)
    {
        List<TInCollect> list = tInCollectService.selectTInCollectList(tInCollect);
        ExcelUtil<TInCollect> util = new ExcelUtil<TInCollect>(TInCollect.class);
        util.exportExcel(response, list, "发票采集数据");
    }

    /**
     * 获取发票采集详细信息
     */
    @PreAuthorize("@ss.hasPermi('doc:collect:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tInCollectService.selectTInCollectById(id));
    }

    /**
     * 新增发票采集
     */
    @PreAuthorize("@ss.hasPermi('doc:collect:add')")
    @Log(title = "发票采集", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TInCollect tInCollect)
    {
        return toAjax(tInCollectService.insertTInCollect(tInCollect));
    }

    /**
     * 修改发票采集
     */
    @PreAuthorize("@ss.hasPermi('doc:collect:edit')")
    @Log(title = "发票采集", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TInCollect tInCollect)
    {
        return toAjax(tInCollectService.updateTInCollect(tInCollect));
    }

    /**
     * 删除发票采集
     */
    @PreAuthorize("@ss.hasPermi('doc:collect:remove')")
    @Log(title = "发票采集", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tInCollectService.deleteTInCollectByIds(ids));
    }

    /**
     * 上传识别文件
     * @param folderId 票夹ID
     * @param files
     * @return
     * @throws Exception
     */
    @PostMapping("/{folderId}/importImg")
    public AjaxResult importImg(@PathVariable("folderId") String folderId, @RequestParam("files") List<MultipartFile> files) throws Exception {
        if(StringUtils.isEmpty(folderId)){
            throw new ServiceException("票夹不能为空！");
        }
        if(CollectionUtils.isEmpty(files)){
            throw new ServiceException("文件不能为空！");
        }
        if(files.size() > MAX_FILE_QTY){
            throw new ServiceException("文件不能超过" + MAX_FILE_QTY + "个！");
        }

        // 票夹对象
        TInInvoiceFolder inInvoiceFolder = tInInvoiceFolderService.selectTInInvoiceFolderByFolderId(folderId);
        if(Objects.isNull(inInvoiceFolder)){
            throw new ServiceException("无效票夹！");
        }
        /*
            将图片保存到本地
         */
        List<InvoiceForRecogcollect> invoiceForRecogcollectList = new ArrayList<InvoiceForRecogcollect>();
        try
        {
            // 上传文件路径
            String filePath = ImsConfig.getUploadPath();
            for (MultipartFile file : files)
            {
                InvoiceForRecogcollect invoiceForRecogcollect = new InvoiceForRecogcollect();
                // 上传并返回新文件名称
                Map<String, String> fileMap = FileUploadUtils.uploadWithAbsPath(filePath, file);
                String url = fileMap.get("fileName");
                String absPath = fileMap.get("absPath");
                invoiceForRecogcollect.setUlr(url);
                invoiceForRecogcollect.setFileName(file.getOriginalFilename());
                String base64 = FileUtils.fileToBase64(absPath);
                invoiceForRecogcollect.setFileBase64(base64);
                invoiceForRecogcollectList.add(invoiceForRecogcollect);
            }
        } catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
        try {
            tInCollectService.inInvoiceRecogcollectByImport(invoiceForRecogcollectList);
        } catch (ServiceException e)
        {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 下载发票Excel模板
     * @param response
     */
    @PostMapping("/importExcelTemplate")
    public void importExcelTemplate(HttpServletResponse response)
    {
        NewExcelUtil<InvoiceCollectValidateVo> util = new NewExcelUtil<InvoiceCollectValidateVo>(InvoiceCollectValidateVo.class);
        util.importTemplateExcel(response, "发票采集导入模板");
    }

    /**
     * 上传发票Excel
     * @param folderId 票夹ID
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("/{folderId}/importExcel")
    public AjaxResult importExcel(@PathVariable("folderId") String folderId, @RequestParam("excelFile") MultipartFile file) throws Exception {
        if(StringUtils.isEmpty(folderId)){
            throw new ServiceException("票夹不能为空！");
        }
        if(file == null){
            throw new ServiceException("文件不能为空！");
        }
        // 票夹对象
        TInInvoiceFolder inInvoiceFolder = tInInvoiceFolderService.selectTInInvoiceFolderByFolderId(folderId);
        if(Objects.isNull(inInvoiceFolder)){
            throw new ServiceException("无效票夹！");
        }
        // 不能超过300行
        ExcelUtil<InvoiceCollectValidateVo> util = new ExcelUtil<InvoiceCollectValidateVo>(InvoiceCollectValidateVo.class);
        List<InvoiceCollectValidateVo> invoiceCollectExcelVoList = util.importExcel(file.getInputStream());
        if(invoiceCollectExcelVoList.size() > MAX_EXCEL_LINE_QTY){
            throw new ServiceException("最大不超过300条数据！");
        }
       /*
            将Excel保存到本地
        */
        try
        {
            // 上传文件路径
            String filePath = ImsConfig.getUploadPath();
            // 文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            // TODO 该文件保存到采集对象中
        } catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
        try {
            tInCollectService.inInvoiceRecogcollectByValidate(invoiceCollectExcelVoList, CollectType.DAO_RU);
        } catch (ServiceException e)
        {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 上传手工导入发票
     * @param folderId
     * @param invoiceCollectExcelVoList
     * @return
     * @throws Exception
     */
    @PostMapping("/{folderId}/importManual")
    public AjaxResult importManual(@PathVariable("folderId") String folderId, List<InvoiceCollectValidateVo> invoiceCollectExcelVoList) throws Exception {
        if(StringUtils.isEmpty(folderId)){
            throw new ServiceException("票夹不能为空！");
        }
        if(CollectionUtils.isEmpty(invoiceCollectExcelVoList)){
            throw new ServiceException("输入列表不能为空！");
        }
        // 票夹对象
        TInInvoiceFolder inInvoiceFolder = tInInvoiceFolderService.selectTInInvoiceFolderByFolderId(folderId);
        if(Objects.isNull(inInvoiceFolder)){
            throw new ServiceException("无效票夹！");
        }
        if(invoiceCollectExcelVoList.size() > MAX_EXCEL_LINE_QTY){
            throw new ServiceException("最大不超过300条数据！");
        }
        try {
            tInCollectService.inInvoiceRecogcollectByValidate(invoiceCollectExcelVoList, CollectType.SHOU_GONGS);
        } catch (ServiceException e)
        {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 上传扫码发票
     * @param folderId
     * @param scanContentList
     * @return
     * @throws Exception
     */
    @PostMapping("/{folderId}/importScan")
    public AjaxResult importScan(@PathVariable("folderId") String folderId, List<String> scanContentList) throws Exception {
        if(StringUtils.isEmpty(folderId)){
            throw new ServiceException("票夹不能为空！");
        }
        if(CollectionUtils.isEmpty(scanContentList)){
            throw new ServiceException("扫码内容不能为空！");
        }
        // 票夹对象
        TInInvoiceFolder inInvoiceFolder = tInInvoiceFolderService.selectTInInvoiceFolderByFolderId(folderId);
        if(Objects.isNull(inInvoiceFolder)){
            throw new ServiceException("无效票夹！");
        }
        if(scanContentList.size() > MAX_EXCEL_LINE_QTY){
            throw new ServiceException("最大不超过300条数据！");
        }
        List<InvoiceCollectValidateVo> invoiceCollectExcelVoList = new ArrayList<>();
        // scanContent 案例  01,32,,24322000000379894766,3294.00,20241002,,1778
        for(String scanContent : scanContentList){
            try {
                InvoiceCollectValidateVo invoiceCollectValidateVo = new InvoiceCollectValidateVo();
                invoiceCollectValidateVo.setInvoiceNumber(scanContent.split(",")[3]);
                String billingDateStr = scanContent.split(",")[5];
                billingDateStr = billingDateStr.substring(0,4) + "-" + billingDateStr.substring(4,6) + "-" + billingDateStr.substring(6,billingDateStr.length());
                invoiceCollectValidateVo.setBillingDate(billingDateStr);
                invoiceCollectExcelVoList.add(invoiceCollectValidateVo);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            tInCollectService.inInvoiceRecogcollectByValidate(invoiceCollectExcelVoList, CollectType.ER_WEI_MA);
        } catch (ServiceException e)
        {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

}
